/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.util;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Charsets;
import org.apache.commons.codec.digest.DigestUtils;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 加密
 */
public class RsaOperor {

    /**
     * 对称加密算法
     */
    private static final String KEY_AES_ALGORITHM = "AES/CBC/PKCS7Padding";

    /**
     * 非对称加密算法
     */
    private static final String KEY_RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";

    /**
     * 密钥长度，DH算法的默认密钥长度是1024
     * 密钥长度必须是64的倍数，在512到65536位之间
     */
    private static final int KEY_SIZE = 1024;

    /**
     * 默认构建方法
     * @return
     * @throws Exception
     */
    public static RsaOperor build() throws Exception {
        return new RsaOperor();
    }

    /**
     *  Description: 解密接收数据
     *  @author  wh.huang  DateTime 2018年11月15日 下午5:06:42
     *  @param publicKey
     * @param selfPrivateKey
     *  @param receiveData
     *  @throws InvalidKeyException
     *  @throws NoSuchPaddingException
     *  @throws NoSuchAlgorithmException
     *  @throws BadPaddingException
     *  @throws IllegalBlockSizeException
     *  @throws UnsupportedEncodingException
     *  @throws InvalidAlgorithmParameterException
     */
    public static String decryptReceivedData(RSAPublicKey publicKey, PrivateKey selfPrivateKey, String receiveData) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
        @SuppressWarnings("unchecked")
        Map<String, String> receivedMap = (Map<String, String>) JSON.parse(receiveData);

        // 解密请求方在发送请求时，加密data字段所用的对称加密密钥
        String a = receivedMap.get("a");
        String b = receivedMap.get("b");
        b = decryptRSA(selfPrivateKey, b);
        a = decryptRSA(selfPrivateKey, a);

        // 解密data数据
        String c = decryptAES(b, a, receivedMap.get("c"));
        System.out.println("接收到的data内容：" + c);
        return c;
    }

    /**
     *  Description: 加密数据
     *  @author  wh.huang DateTime 2018年11月15日 下午5:20:11
     *  @param externalPublicKey
     *  @param selfPrivateKey
     *  @return 加密后的待发送数据
     *  @throws NoSuchAlgorithmException
     *  @throws InvalidKeyException
     *  @throws NoSuchPaddingException
     *  @throws UnsupportedEncodingException
     *  @throws BadPaddingException
     *  @throws IllegalBlockSizeException
     *  @throws InvalidAlgorithmParameterException
     */
    public static String encryptSendData(PublicKey externalPublicKey, PrivateKey selfPrivateKey, JSONObject sendData) throws NoSuchAlgorithmException,
            InvalidKeyException, NoSuchPaddingException, BadPaddingException,
            IllegalBlockSizeException, InvalidAlgorithmParameterException {

        // 随机生成对称加密的密钥和IV (IV就是加盐的概念，加密的偏移量)
        String aesKeyWithBase64 = genRandomAesSecretKey();
        String aesIVWithBase64 = genRandomIV();

        //用上面生成的对称加密的密钥和IV进行加密
        String cipherData = encryptAES(aesKeyWithBase64, aesIVWithBase64, sendData.toJSONString());

        // 用服务方提供的公钥加密key和salt，服务方会用对应的私钥解密
        String a = encryptRSA(externalPublicKey, aesIVWithBase64);
        String b = encryptRSA(externalPublicKey, aesKeyWithBase64);

        // 组织请求的key、value对
        Map<String, String> requestMap = new TreeMap<>();
        requestMap.put("b", b);
        requestMap.put("a", a);
        requestMap.put("c", cipherData);

        String privateKey = Base64.getEncoder().encodeToString(selfPrivateKey.getEncoded());
        requestMap.put("d",privateKey);

        JSONObject json = new JSONObject();
        json.putAll(requestMap);
        return json.toString();
    }

    /**
     *  Description: 加密数据
     *  @author  wh.huang DateTime 2018年11月15日 下午5:20:11
     *  @param externalPublicKey
     *  @param selfPrivateKey
     *  @return 加密后的待发送数据
     *  @throws NoSuchAlgorithmException
     *  @throws InvalidKeyException
     *  @throws NoSuchPaddingException
     *  @throws UnsupportedEncodingException
     *  @throws BadPaddingException
     *  @throws IllegalBlockSizeException
     *  @throws InvalidAlgorithmParameterException
     */
    public static String encryptSendData(PublicKey externalPublicKey, PrivateKey selfPrivateKey,String sendData) throws NoSuchAlgorithmException,
            InvalidKeyException, NoSuchPaddingException, BadPaddingException,
            IllegalBlockSizeException, InvalidAlgorithmParameterException {

        // 随机生成对称加密的密钥和IV (IV就是加盐的概念，加密的偏移量)
        String aesKeyWithBase64 = genRandomAesSecretKey();
        String aesIVWithBase64 = genRandomIV();

        //用上面生成的对称加密的密钥和IV进行加密
        String cipherData = encryptAES(aesKeyWithBase64, aesIVWithBase64, sendData);

        // 用服务方提供的公钥加密key和salt，服务方会用对应的私钥解密
        String a = encryptRSA(externalPublicKey, aesIVWithBase64);
        String b = encryptRSA(externalPublicKey, aesKeyWithBase64);

        // 组织请求的key、value对
        Map<String, String> requestMap = new TreeMap<>();
        requestMap.put("b", b);
        requestMap.put("a", a);
        requestMap.put("c", cipherData);

        String privateKey = Base64.getEncoder().encodeToString(selfPrivateKey.getEncoded());
        requestMap.put("d",privateKey);

        JSONObject json = new JSONObject();
        json.putAll(requestMap);
        return json.toString();
    }

    /**
     * 根据公钥字符串生成公钥对象
     * @param base64PublicKey
     * @return
     */
    public static PublicKey generatePublicKey(String base64PublicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] keyBytes = Base64.getDecoder().decode(base64PublicKey.getBytes(Charsets.UTF_8));
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * 根据私钥字符串生成私钥对象
     * @param base64PrivateKey
     * @return
     */
    public static PrivateKey generatePrivateKey(String base64PrivateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        PKCS8EncodedKeySpec priPKCS8;
        priPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64PrivateKey.getBytes(Charsets.UTF_8)));
        KeyFactory keyf = KeyFactory.getInstance("RSA");
        return keyf.generatePrivate(priPKCS8);
    }

    /**
     * 计算sha256值
     *
     * @param paramMap
     * @return 签名后的所有数据，原始数据+签名
     */
    private static String sha256(Map<String, String> paramMap) {
        Map<String, String> params = new TreeMap<String, String>(paramMap);

        StringBuilder concatStr = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if ("sign".equals(entry.getKey())) {
                continue;
            }
            concatStr.append(entry.getKey() + "=" + entry.getValue() + "&");
        }
        return DigestUtils.md5Hex(concatStr.toString());
    }

    /**
     *  获取随机的对称加密的密钥
     *  @author  wh.huang  DateTime 2018年11月15日 下午5:25:53
     *  @return  对称秘钥字符
     *  @throws NoSuchAlgorithmException
     *  @throws UnsupportedEncodingException
     *  @throws IllegalBlockSizeException
     *  @throws BadPaddingException
     *  @throws InvalidKeyException
     *  @throws NoSuchPaddingException
     */
    private static String genRandomAesSecretKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey secretKey = keyGen.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

    /**
     *
     * @return
     */
    private static String genRandomIV() {
        SecureRandom r = new SecureRandom();
        byte[] iv = new byte[16];
        r.nextBytes(iv);
        return Base64.getEncoder().encodeToString(iv);
    }

    /**
     * 对称加密数据
     * @param keyWithBase64
     * @param plainText
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     * @throws InvalidAlgorithmParameterException
     */
    private static String encryptAES(String keyWithBase64, String ivWithBase64, String plainText)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
            BadPaddingException, InvalidAlgorithmParameterException {
        byte[] keyWithBase64Arry = keyWithBase64.getBytes();
        byte[] ivWithBase64Arry = ivWithBase64.getBytes();
        SecretKeySpec key = new SecretKeySpec(Base64.getDecoder().decode(keyWithBase64Arry), "AES");
        IvParameterSpec iv = new IvParameterSpec(Base64.getDecoder().decode(ivWithBase64Arry));
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance(KEY_AES_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
        return Base64.getEncoder().encodeToString(cipher.doFinal(plainText.getBytes(Charsets.UTF_8)));
    }

    /**
     * 对称解密数据
     *
     * @param keyWithBase64
     * @param cipherText
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     * @throws InvalidAlgorithmParameterException
     */
    private static String decryptAES(String keyWithBase64, String ivWithBase64, String cipherText)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
            BadPaddingException, InvalidAlgorithmParameterException {
        byte[] keyWithBase64Arry = keyWithBase64.getBytes();
        byte[] ivWithBase64Arry = ivWithBase64.getBytes();
        byte[] cipherTextArry = cipherText.getBytes();
        SecretKeySpec key = new SecretKeySpec(Base64.getDecoder().decode(keyWithBase64Arry), "AES");
        IvParameterSpec iv = new IvParameterSpec(Base64.getDecoder().decode(ivWithBase64Arry));
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance(KEY_AES_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
        return new String(cipher.doFinal(Base64.getDecoder().decode(cipherTextArry)), Charsets.UTF_8);
    }

    /**
     * 非对称加密，根据公钥和原始内容产生加密内容
     * @param key
     * @param plainText
     * @return
     * @throws NoSuchPaddingException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws UnsupportedEncodingException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     * @throws InvalidAlgorithmParameterException
     */
    private static String encryptRSA(Key key, String plainText)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = Cipher.getInstance(KEY_RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return Base64.getEncoder().encodeToString(cipher.doFinal(plainText.getBytes(Charsets.UTF_8))).toString();
    }

    /**
     * 根据私钥和加密内容产生原始内容
     * @param key
     * @param content
     * @return
     * @throws NoSuchPaddingException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     * @throws UnsupportedEncodingException
     * @throws InvalidAlgorithmParameterException
     */
    private static String decryptRSA(Key key, String content) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
        Cipher cipher = Cipher.getInstance(KEY_RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] contentArry = content.getBytes();
        return new String(cipher.doFinal(Base64.getDecoder().decode(contentArry)), Charsets.UTF_8);
    }

    /**
     * 创建RSA的公钥和私钥对
     * @throws NoSuchAlgorithmException
     */
    public static Map<String,Object> createKeyPairs() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        Map<String,Object> keyMap = new HashMap<>();
        keyMap.put("public",publicKey);
        keyMap.put("private",privateKey);
        return keyMap;
    }

    /**
     * 打钢戳
     * <p>
     *      打钢戳过程描述：
     *      1、最终打出包的文件为upgrade.license，其主要是根据用户的私钥，唯一码和升级包的编码生成的升级包证书文件。
     *      2、加密算法：
     *      a> 使用公钥对数据进行加密。
     *      b> 使用私钥对数据进行解密。
     * <p/>
     * @param zipFile
     * @param licensePublicKey
     * @param licenseId
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws IllegalBlockSizeException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws NoSuchPaddingException
     * @throws InvalidAlgorithmParameterException
     * @throws IOException
     */
    public static File addStamp(File zipFile, String licensePublicKey, String licenseId) throws NoSuchAlgorithmException,
            InvalidKeySpecException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException,
            NoSuchPaddingException, InvalidAlgorithmParameterException, IOException {

        //生成AES秘钥
        String accessKey = genRandomAesSecretKey();
        //生成偏移量
        String iv = genRandomIV();
        //对秘钥和偏移量进行RSA加密
        PublicKey publicKey = generatePublicKey(licensePublicKey);
        String encryptAccessKey = encryptRSA(publicKey,accessKey);
        String encryptIv = encryptRSA(publicKey,iv);
        //加密的数据
        JSONObject datas = new JSONObject();
        datas.put("licenseId",licenseId);
        String encrptData = encryptAES(accessKey,iv,datas.toJSONString());
        String licensePath = String.format("%s/%s",zipFile.getParent(),licenseId);
        if(!FileUtil.exist(licensePath)){
            FileUtil.mkdir(licensePath);
        }

        String unzipPath = String.format("%s/%s",licensePath,"sources");
        if(!FileUtil.exist(unzipPath)){
            FileUtil.mkdir(unzipPath);
        }

        File unzipSourceDir = new File(unzipPath);
        if(!FileUtil.isDirEmpty(unzipSourceDir)){
            FileUtil.clean(unzipPath);
        }

        //解压到证书下
        ZipUtil.unzip(zipFile,new File(unzipPath));
        //解压后，读取JSON串
        File upgradeJsonFile = new File(String.format("%s/%s",unzipPath,"upgrade.json"));
        if(!upgradeJsonFile.exists()){
            throw new FileNotFoundException("没有找到升级描述文件！");
        }
        String upgardeJson = FileUtil.readString(upgradeJsonFile, Charsets.UTF_8);
        JSONObject upgradeJsonObj = JSON.parseObject(upgardeJson);
        upgradeJsonObj.put("UPPACKAGE_FIELDA",encryptAccessKey);
        upgradeJsonObj.put("UPPACKAGE_FIELDB",encryptIv);
        upgradeJsonObj.put("UPPACKAGE_FIELDC",encrptData);
        FileUtil.writeBytes(upgradeJsonObj.toJSONString().getBytes(Charsets.UTF_8),upgradeJsonFile);
        String fileName = zipFile.getName().substring(0,zipFile.getName().lastIndexOf("."));
        return ZipUtil.zip(unzipPath,String.format("%s/%s",licensePath,String.format("%s-%s.%s",fileName,System.currentTimeMillis(),"zip")));
    }

    /**
     * 钢戳验证
     * @param upgradeJsonAbsoluteFilePath
     * @param license
     * @return
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidAlgorithmParameterException
     * @throws UnsupportedEncodingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws InvalidKeyException
     */
    public static boolean stampVerify(String upgradeJsonAbsoluteFilePath,String license) throws InvalidKeySpecException, NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException, IllegalBlockSizeException,
            BadPaddingException, InvalidKeyException {

        //解密信息
        JSONObject licenseObj = JSON.parseObject(license);
        String d = licenseObj.getString("d");
        PrivateKey nameKey = RsaDecoder.generatePrivateKey(d);
        String nameValue = RsaDecoder.decryptReceivedData(nameKey,license);
        JSONObject nameObj = JSON.parseObject(nameValue);

        //解密升级包中的信息
        String upgradeJson = FileUtil.readString(upgradeJsonAbsoluteFilePath, Charsets.UTF_8);
        JSONObject upgradeJsonObj = JSON.parseObject(upgradeJson);
        String fieldA = upgradeJsonObj.getString("UPPACKAGE_FIELDA");
        String fieldB = upgradeJsonObj.getString("UPPACKAGE_FIELDB");
        String fieldC = upgradeJsonObj.getString("UPPACKAGE_FIELDC");
        PrivateKey privteKeyObj = generatePrivateKey(d);
        String decrptFieldA = decryptRSA(privteKeyObj,fieldA);
        String decrptFieldB = decryptRSA(privteKeyObj,fieldB);
        String decrptFieldC = decryptAES(decrptFieldA,decrptFieldB,fieldC);
        JSONObject data = JSON.parseObject(decrptFieldC);

        //进行校验
        if(data.containsKey("licenseId") && nameObj.containsKey("o") && data.getString("licenseId").equals(nameObj.getString("o"))){
            return true;
        }
        return false;
    }
}

